package com.microservices.yucloud.api.consumer;

import com.microservices.yucloud.api.entity.Email;
import com.microservices.yucloud.api.queue.WorkerQueue;
import com.microservices.yucloud.api.service.EmailService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Component;

import javax.annotation.PostConstruct;
import javax.annotation.PreDestroy;
import java.util.concurrent.TimeUnit;

/**
 * @author zy
 * @date 2019-08-14 17:28
 */
@Slf4j
@Component
public class EmailConsumer {

    @Autowired
    @Qualifier("threadPoolTaskExecutor")
    private TaskExecutor executor;

    @Autowired
    private EmailService emailService;

    @PostConstruct
    public void startThread() {
        log.info("EmailConsumer 队列消费开启");
        executor.execute(new PollMail());
    }

    class PollMail implements Runnable {

        @Override
        public void run() {
            while (true) {
                executor.execute(() -> {
                    try {
                        Email mail = WorkerQueue.getMailQueue().consume();
                        if (mail != null) {
                            log.info("消费邮件任务:{}", mail.getEmail());
                            mail.setStatus(2);
                            emailService.updateEmail(mail);
                            log.info("待处理邮件任务数量:[{}]", emailService.selectEmailTasks().size());
                        }else {
                            TimeUnit.MILLISECONDS.sleep(3000);
                        }
                        log.info("队列剩余任务总数:[{}]", WorkerQueue.getMailQueue().size());
                    } catch (Exception e) {
                        log.error("消费任务异常", e);
                    }
                });
            }
        }
    }

    @PreDestroy
    public void stopThread() {
        log.info("destroy");
    }
}
